﻿using Qs.Repository.Domain;
using Qs.Repository;
using System;
using Qs.Comm.Cache;
using Qs.Repository.Interface;
using Qs.Comm;
using System.Globalization;

namespace Qs.App
{
    /// <summary>
    ///  缓存
    /// </summary>
    public class AppCacheComm
    {
        IUnitWork<QsDBContext> _unitWork;
        private ICacheContext _cacheContext;
        /// <summary>
        ///  构造函数
        /// </summary>
        /// <param name="unitWork"></param>
        /// <param name="cacheContext"></param>
        /// <param name="dbExtension"></param>
        public AppCacheComm(IUnitWork<QsDBContext> unitWork, ICacheContext cacheContext, DbExtension dbExtension)
        {
            _unitWork = unitWork;
            _cacheContext = cacheContext;
        }

        /// <summary>
        /// 获取StoreId缓存
        /// </summary>
        /// <param name="appId"></param>
        /// <returns></returns>
        public string GetStoreId(string appId)
        {
            var strKey = $"StoreId{appId}";
            var storeId = _cacheContext.Get<string>(strKey);
            if (string.IsNullOrEmpty(storeId))
            {
                var setting = _unitWork.FirstOrDefault<ModelStoreSetting>(p => p.Key == DefineSetting.BasicWxApp && p.Values.Contains(appId));
                if (setting == null)
                {
                    throw new Exception($"请先配置小程序信息(管理端=>客户端=>微信小程序=>小程序设置)");
                }
                storeId = setting.StoreId;
                _cacheContext.Set<string>(strKey, storeId, DateTime.Now.AddHours(12));
            }
            return storeId;
        }

        /// <summary>
        /// 移除Token缓存
        /// </summary>
        /// <param name="token"></param>
        public void RemoveToken(string token)
        {
            _cacheContext.Remove(token);
        }

        /// <summary>
        /// 设置验证码缓存
        /// </summary>
        /// <param name="verifyCodeId"></param>
        /// <param name="code"></param>
        public void SetVerifyCode(string verifyCodeId, string code)
        {
            _cacheContext.Set(verifyCodeId, code, DateTime.Now.AddMinutes(5));
        }


    }
}
